package zj.it.bhne.gridengineeringsurvey.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.entity.Equip;
import zj.it.bhne.gridengineeringsurvey.entity.EquipType;
import zj.it.bhne.gridengineeringsurvey.entity.ModelType;
import zj.it.bhne.gridengineeringsurvey.entity.bean.Module;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Equipment;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Line;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Points;
import zj.it.bhne.gridengineeringsurvey.myutils.MyUtils;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.EquipmentDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.LineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PointsDao;

import static zj.it.bhne.gridengineeringsurvey.activity.EquActivity.setSpinnerItemSelectedByValue;
import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.Distance;
import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.openDatabase;


/**
 * 修改线属性的活动
 */
public class LineActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private Long aid;
    private Long bid;
    private Long cid;
    private Long line_id;
    private Spinner line_sp_sort;
    private Spinner line_sp_b;
    private Points points_a, points_b;
    private Spinner line_sp_statue;
    private EditText line_tv_line_hui;
    private EditText line_tv_line_gen;
    private LinearLayout linearLayout;
    private List<Equipment> equipmentList = new ArrayList<>();
    private List<Equip> equipList = getGuPiaoDai(3);
    private int lever;
    private List<ModuleType> string = new ArrayList<>();
    private int two = 0;
    private Spinner line_sp_type;
    private int four;
    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> modelTypes = new ArrayList<>();
    private List<Module> modules=new ArrayList<>();
    private String moduleId="",moduleName="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line);
        initView();
        context = this;
        Intent intent = getIntent();
        aid = intent.getLongExtra("aid", 0);
        bid = intent.getLongExtra("bid", 0);
        cid = intent.getLongExtra("cid", 0);
        line_id = intent.getLongExtra("line_id", 0);
        initViewData();
    }

    public List<Equip> getGuPiaoDai(int str) {
        List<Equip> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Equip equip = new Equip();
            equip.setId(cursor.getInt(0));
            equip.setName(cursor.getString(1));
            equip.setCode(cursor.getString(4));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 初始化数据
     */
    @SuppressLint("SetTextI18n")
    private void initViewData() {

        line_sp_sort = findViewById(R.id.line_sp_sort);

        Line lines = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Id.eq(line_id)).build().list().get(0);

        line_tv_line_hui.setText(lines.getBackNum());
        line_tv_line_gen.setText(lines.getNum());

        List<String> sp_sort = new ArrayList<>();
        //TODO 这里一堆进行
        if (lines.getType()!=null&&!lines.getType().isEmpty()) {
            for (int i = 0; i < equipList.size(); i++) {
                if (lines.getType().equals(equipList.get(i).getName())) {
                    sp_sort.add(equipList.get(i).getName());
                    Collections.swap(sp_sort,i,0);
                    Collections.swap(equipList,i,0);
                }else{
                    sp_sort.add(equipList.get(i).getName());
                }
            }
        }else{
            for (int i = 0; i < equipList.size(); i++) {
                sp_sort.add(equipList.get(i).getName());
            }
            Collections.swap(sp_sort,2,0);
            Collections.swap(equipList,2,0);
        }

        //适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, sp_sort);
        //设置样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        line_sp_sort.setAdapter(adapter);
        //setSpinnerItemSelectedByValue(line_sp_sort, lines.getType());
        line_sp_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                lever = equipList.get(position).getId();
                List<Integer> list = new ArrayList<>();
                list.clear();
                //TODO 这里去equip_ModelType拿moduleTypeID
                List<EquipType> equipTypeData = getEquipIdList(lever);
                for (int i = 0; i < equipTypeData.size(); i++) {
                    list.add(equipTypeData.get(i).getModuleTypeID());
                }
                string.clear();
                string = getGuPiao(list);
                //TODO 这里去最后一个最后一个表进查询
                modules.clear();
                modules=getResultModule(string);
                final List<String> adapter_data4 = new ArrayList<>();
                adapter_data4.clear();
                if (lines.getTypes()!=null&&!lines.getTypes().isEmpty()) {
                    for (int s = 0; s < modules.size(); s++) {
                        if (lines.getTypes().equals(modules.get(s).getModuleName())) {
                            adapter_data4.add(modules.get(s).getModuleName());
                            Collections.swap(adapter_data4, s, 0);
                        } else {
                            adapter_data4.add(modules.get(s).getModuleName());
                        }
                    } //适配器
                }else {
                    for (int s = 0; s < modules.size(); s++) {
                        adapter_data4.add(modules.get(s).getModuleName());
                    } //适配器
                }
                ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(LineActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                //设置样式
                arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                line_sp_type.setAdapter(arr_adapter4);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // Log.e("strring",lines.getTypes());
        //setSpinnerItemSelectedByValue(line_sp_type, lines.getTypes());
        line_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //two = Integer.parseInt(modules.get(position).getModuleCode());
                moduleId=modules.get(position).getModuleID();
                moduleName=modules.get(position).getModuleName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        setSpinnerItemSelectedByValue(line_sp_statue, lines.getStatue());
        Button line_btn_save = findViewById(R.id.line_btn_save);
        equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(line_id), EquipmentDao.Properties.Qubie.eq(1)).build().list();
        line_btn_save.setOnClickListener(this);
        points_a = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(aid)).build().list().get(0);
        points_b = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(bid)).build().list().get(0);

        List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();

        TextView line_tv_name = findViewById(R.id.line_tv_name);
        line_tv_name.setText(points_b.getMark() + "");
        TextView line_tv_dj = findViewById(R.id.line_tv_dj);
        line_tv_dj.setText(points_b.getDangju() + "米");
        line_sp_b = findViewById(R.id.line_sp_b);
        List<String> adapter_data = new ArrayList<>();
        for (int i = 0; i < pointsList.size(); i++) {
            adapter_data.add(pointsList.get(i).getMark());
        }
        //适配器
        ArrayAdapter<String> sp_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data);
        //设置样式
        sp_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        line_sp_b.setAdapter(sp_adapter);
        if (points_b.getGlsb() != null)
            setSpinnerItemSelectedByValue(line_sp_b, points_b.getGlsb());
        linearLayout = getWindow().getDecorView().findViewById(R.id.line_ll);

        //添加的设备不为空时，添加新的View
        if (equipmentList.size() > 0) {
            linearLayout.removeAllViews();
            for (int i = 0; i < equipmentList.size(); i++) {
                View view = View.inflate(context, R.layout.activity_equ_equ, null);
                TextView equ_ed_lever = view.findViewById(R.id.equ_ed_lever);
                TextView equ_tv_name = view.findViewById(R.id.equ_tv_name);
                TextView equ_tv_xuan = view.findViewById(R.id.equ_tv_xuan);
                TextView equ_tv_amount = view.findViewById(R.id.equ_tv_amount);
                Button equ_btn_delete = view.findViewById(R.id.equ_btn_delete);
                equ_ed_lever.setText(equipmentList.get(i).getTwo_name());
                equ_tv_name.setText(equipmentList.get(i).getName());
                equ_tv_amount.setText(equipmentList.get(i).getAmount() + "");
                linearLayout.addView(view);
                final int finalI = i;
                equ_btn_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (equipmentList.size() > 1) {
                            MyApplication.getInstances().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                            initViewData();
                        } else {
                            MyApplication.getInstances().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                            linearLayout.removeAllViews();
                        }

                    }
                });
                equ_tv_xuan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        addEqu(equipmentList.get(finalI).getId());
                    }
                });
            }
        }
    }

    /**
     * 这里去Module里面进行线端查询最后的结果
     *
     * @param string
     */
    private List<Module> getResultModule(List<ModuleType> string) {
        List<Module> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor;
        for (int i = 0; i < string.size(); i++) {
            cursor = db.rawQuery("select * from Module where ModuleTypeKey=" + "'" + string.get(i).getModuleTypeKey() + "'", null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                Module equip = new Module();
                equip.setModuleID(cursor.getString(0));
                equip.setModuleName(cursor.getString(1));
                equip.setModuleTypeKey(cursor.getString(2));
                equip.setModuleCode(cursor.getString(3));
                strings.add(equip);
            }
            cursor.close();
        }

        db.close();
        return strings;
    }


    /**
     * 按钮点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.line_btn_save:
                save();
                break;
            case R.id.activity_ib_back:
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.activity_tv_save:
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.equ_btn_equ:
                addEqu((long) -20);
                //MyUtils.getToast(context,"暂未开放");
                break;
        }
    }

    /**
     * 获取数据库中的数据
     */
    public List<ModelType> getGuPiaoDaiMA(int str) {
        List<ModelType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(LineActivity.this);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModelType modelType = new ModelType();
            modelType.setId(cursor.getInt(0));
            modelType.setName(cursor.getString(1));
            modelType.setParentid(cursor.getInt(2));
            strings.add(modelType);
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 获取数据库中的数据
     */
    public List<ModuleType> getGuPiao(List<Integer> str) {
        List<ModuleType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(LineActivity.this);
        Cursor cursor = null;

        for (int i = 0; i < str.size(); i++) {
            cursor = db.rawQuery("select * from ModuleType where ModuleTypeID=" + str.get(i), null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                ModuleType equip = new ModuleType();
                equip.setModuleTypeID(cursor.getString(0));
                equip.setName(cursor.getString(1));
                equip.setModuleTypeKey(cursor.getString(2));
                strings.add(equip);
            }
            cursor.close();
        }

        db.close();
        return strings;
    }

    /**
     * 添加设备
     */
    private void addEqu(final Long num) {
        final View views = View.inflate(context, R.layout.activity_line_dialog, null);
        final Spinner map_ed_lever = views.findViewById(R.id.map_ed_lever);
        final Spinner map_ed_head = views.findViewById(R.id.map_ed_head);
        Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
        final Spinner map_sp_three = views.findViewById(R.id.map_sp_three);

        Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
        final EditText map_ed_four = views.findViewById(R.id.map_ed_four);
        final List<ModelType> stringss = getGuPiaoDaiMA(3);
        final List<String> adapter_data21 = new ArrayList<>();
        for (int s = 0; s < stringss.size(); s++) {
            adapter_data21.add(stringss.get(s).getName());
        }
        //TODO 第一级设备类型
        ArrayAdapter<String> arr_adapter21 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data21);
        //设置样式
        arr_adapter21.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        map_ed_lever.setAdapter(arr_adapter21);

        map_ed_lever.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                lever = stringss.get(position).getId();
                List<Integer> list;
                list = getModuleTypeID(stringss.get(position).getId());
                //TODO 获取二级下啦列表
                string = getGuPiao(list);
                Log.e("stringall", string.toString());
                final List<String> adapter_data4 = new ArrayList<>();

                for (ModuleType moduleType : string) {
                    adapter_data4.add(moduleType.getName());
                }
                //适配器
                ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(LineActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                //设置样式
                arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_ed_head.setAdapter(arr_adapter4);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        map_ed_head.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                two = Integer.parseInt(string.get(position).getModuleTypeID());
                modelTypes = getModuleAll(string.get(position).getModuleTypeKey());
                two = Integer.parseInt(string.get(position).getModuleTypeID());
                final List<String> adapter_data4 = new ArrayList<>();
                adapter_data4.clear();
                /*String str = "(a >= 0 && a <= 5)";
                ScriptEngineManager manager = new ScriptEngineManager();
                ScriptEngine engine = manager.getEngineByName("js");
                engine.put("a", 4);
                Object result = engine.eval(str);
                System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);*/
                if (modelTypes.size() > 0) {
                    map_sp_three.setVisibility(View.VISIBLE);
                    for (int s = 0; s < modelTypes.size(); s++) {
                        adapter_data4.addAll(getModuleLast(modelTypes.get(s).getModuleTypeKey()));
                        Log.e("rrrrr=", modelTypes.get(s).getModuleTypeName());
                    }//适配器
                    //适配器
                    ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(LineActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                    //设置样式
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    map_sp_three.setAdapter(arr_adapter4);
                } else {
                    map_sp_three.setVisibility(View.VISIBLE);

                    adapter_data4.addAll(getModuleLast(string.get(position).getModuleTypeKey()));
                    //适配器
                    ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(LineActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                    //设置样式
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    map_sp_three.setAdapter(arr_adapter4);
                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setView(views);
        dialog.show();
        map_btn_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                KeyboardUtils.hideSoftInput(views);
                dialog.dismiss();
            }
        });
        map_btn_queding.setOnClickListener(view -> {
            KeyboardUtils.hideSoftInput(views);
            dialog.dismiss();
            if (num > 0) {
                Equipment equipment = new Equipment();
                equipment.setName(map_ed_lever.getSelectedItem().toString().trim());
                equipment.setLever_id(lever);
                equipment.setHead_id(two);
                equipment.setTwo_name(map_ed_head.getSelectedItem().toString().trim());
                equipment.setId(num);
                if (map_ed_four.getText().toString().trim().equals("")) {
                    equipment.setAmount(1);
                } else {
                    equipment.setAmount(Integer.parseInt(map_ed_four.getText().toString().trim()));
                }
                equipment.setThree_id(four);
                equipment.setPoint_id(line_id);
                equipment.setQubie(1);
                MyApplication.getInstances().getEquipmentDao().update(equipment);
            } else {
                Equipment equipment = new Equipment();
                equipment.setPoint_id(line_id);
                equipment.setId(null);
                equipment.setQubie(1);
                equipment.setName(map_ed_lever.getSelectedItem().toString().trim());
                equipment.setLever_id(lever);
                equipment.setHead_id(two);
                equipment.setThree_id(four);
                if (map_ed_four.getText().toString().trim().equals("")) {
                    equipment.setAmount(1);
                } else {
                    equipment.setAmount(Integer.parseInt(map_ed_four.getText().toString().trim()));
                }
                equipment.setTwo_name(map_ed_head.getSelectedItem().toString().trim());
                MyApplication.getInstances().getEquipmentDao().insert(equipment);
            }
            initViewData();
        });
    }

    /**
     * 通过设备的父类获取子类集合
     *
     * @param parent 父类唯一标识
     * @return 子类集合
     */
    List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> moduleTypesData = new ArrayList<>();

    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> getModuleAll(String parent) {
        List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> stringsModule = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ParentKey=" + "'" + parent + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType equip = new zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setModuleTypeName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setParentKey(cursor.getString(3));
            stringsModule.add(equip);
        }
        cursor.close();
        db.close();
        moduleTypesData.addAll(stringsModule);

        if (stringsModule.size() > 0) {
            for (int i = 0; i < stringsModule.size(); i++) {
                getModuleAll(stringsModule.get(i).getModuleTypeKey());
            }
        } else {
            return moduleTypesData;
        }
        return moduleTypesData;
    }

    /**
     * 获取最后一个设备
     *
     * @param moduleTypeKey 设备的key
     * @return 设备集合
     */
    private List<String> getModuleLast(String moduleTypeKey) {
        List<String> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(this);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module where ModuleTypeKey=" + "'" + moduleTypeKey + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            strings.add(cursor.getString(1));
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * @param lever 这个用来获取设备id的
     */
    private List<EquipType> getEquipIdList(int lever) {
        List<EquipType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from equip_moduleType where equipID=" + "'" + lever + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            EquipType equip = new EquipType();
            equip.setId(cursor.getInt(0));
            equip.setEquipID(cursor.getInt(1));
            equip.setModuleTypeID(cursor.getInt(2));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 通过设备的父类获取子类集合
     *
     * @param parent 父类唯一标识
     * @return 子类集合
     */
    private List<ModuleType> getModuleWf(String parent) {
        List<ModuleType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ParentKey=" + "'" + parent + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType equip = new ModuleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setParentKey(cursor.getString(3));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    private List<ModuleType> getModule(String parent) {
        List<ModuleType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ParentKey=" + "'" + parent + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType equip = new ModuleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setParentKey(cursor.getString(3));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 根据equipid获取moduletypeid
     *
     * @param id
     * @return
     */
    private List<Integer> getModuleTypeID(int id) {
        List<Integer> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(this);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from 'equip_moduleType' where equipID=" + id, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            strings.add(cursor.getInt(2));
        }
        cursor.close();
        db.close();
        return strings;
    }


    /**
     * 获取数据库中的数据
     */
    public List<ModelType> getLast(int str) {
        List<ModelType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(LineActivity.this);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from moduleTemplate where modelTypeID=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModelType modelType = new ModelType();
            modelType.setId(cursor.getInt(0));
            modelType.setName(cursor.getString(1));
            modelType.setParentid(cursor.getInt(2));
            strings.add(modelType);
        }
        cursor.close();
        db.close();
        return strings;
    }

    private void save() {
        //这里储存Module信息
        /*Equipment equipment = new Equipment();
        equipment.setName(line_sp_sort.getSelectedItem().toString().trim());
        equipment.setLever_id(lever);
        equipment.setModuleID(moduleId);
        equipment.setHead_id(two);
        equipment.setModuleTxt("这里是线哦");
        equipment.setPoint_id(line_id);
        //TODO 1是线
        equipment.setQubie(1);
        MyApplication.getInstances().getEquipmentDao().update(equipment);*/

        points_b.setGlsb(line_sp_b.getSelectedItem().toString().trim());
        points_b.setLineType(line_sp_sort.getSelectedItem().toString().trim());
        points_b.setLinetype(line_sp_type.getSelectedItem().toString().trim());
        MyApplication.getInstances().getPointsDao().update(points_b);
        final List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Mark.eq(line_sp_b.getSelectedItem().toString().trim())).build().list();
        if (pointsList.size() > 0) {
            BigDecimal bg = new BigDecimal(Distance(Double.valueOf(points_b.getLat()), Double.valueOf(points_b.getLon()), Double.valueOf(points_a.getLat()), Double.valueOf(points_a.getLon()))).setScale(2, RoundingMode.UP);
            double lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            Line line = null;
            try {
                line = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Id.eq(line_id)).build().list().get(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Points points = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Mark.eq(line_sp_b.getSelectedItem().toString().trim())).build().list().get(0);
            try {
                line.setLatB(pointsList.get(0).getLat());
                line.setLonB(pointsList.get(0).getLon());
                line.setStart_id(points_b.getUid());
                line.setEnd_id(points.getUid());
                line.setModuleID(moduleId);
                line.setModuleTxt(moduleName);
                line.setLength(lengths + "");
                if (!line_tv_line_hui.getText().toString().trim().equals("")) {
                    line.setBackNum(line_tv_line_hui.getText().toString().trim());
                } else {
                    line.setBackNum("1");
                }
                if (!line_tv_line_gen.getText().toString().trim().equals("")) {
                    line.setNum(line_tv_line_gen.getText().toString().trim());
                } else {
                    line.setNum("1");
                }
                line.setStatue(line_sp_statue.getSelectedItem().toString().trim());
                for (int i = 0; i < equipList.size(); i++) {
                    if (line_sp_sort.getSelectedItem().toString().trim().equals(equipList.get(i).getName())) {
                        line.setName(equipList.get(i).getName() + "-" + line.getId() + "#");
                        line.setType(equipList.get(i).getName());
                        line.setTypes(line_sp_type.getSelectedItem().toString().trim());
                        line.setType_Id(equipList.get(i).getId() + "");
                    }
                }
                MyApplication.getInstances().getLineDao().update(line);
            } catch (Exception e) {
                e.printStackTrace();
            }

            /*line.setName(line_sp_type.getSelectedItem().toString().trim() + "-" + line.getId() + "#");
            line.setType(line_sp_type.getSelectedItem().toString().trim());
            line.setType_Id(two + "");*/


        }


        MyUtils.getToast(context, "修改成功");
        startActivity(new Intent(context, MapActivity.class));

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

    private void initView() {
        ImageButton activity_ib_back = findViewById(R.id.activity_ib_back);
        TextView activity_tv_title = findViewById(R.id.activity_tv_title);
        TextView activity_tv_save = findViewById(R.id.activity_tv_save);
        activity_tv_title.setText("线路");
        activity_tv_save.setText(getString(R.string.map_quxiao));
        activity_ib_back.setOnClickListener(this);
        activity_tv_save.setOnClickListener(this);
        TextView equ_btn_equ = findViewById(R.id.equ_btn_equ);
        equ_btn_equ.setOnClickListener(this);
        line_sp_statue = findViewById(R.id.line_sp_statue);
        line_tv_line_hui = findViewById(R.id.line_tv_line_hui);
        line_tv_line_gen = findViewById(R.id.line_tv_line_gen);
        line_sp_type = findViewById(R.id.line_sp_type);
    }


}
